#include "filebrowserwindow.h"

#include <QVBoxLayout>

FileBrowserWindow::FileBrowserWindow(QWidget *parent) : QMainWindow(parent)
{
    p_engineClient = new EngineClient();
    v_path = "/";

    p_engineClient->connectToHost("127.0.0.1", 5004);

    p_fileTreeListWidget = new QListWidget(this);
    p_pathLineEdit = new QLineEdit();
    QVBoxLayout *vbox = new QVBoxLayout();
    QWidget *wdg = new QWidget();

    vbox->addWidget(p_pathLineEdit);
    vbox->addWidget(p_fileTreeListWidget);

    wdg->setLayout(vbox);
    this->setCentralWidget(wdg);

    QObject::connect(p_fileTreeListWidget, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(explore(QModelIndex)));


    p_engineClient->getSignalFactoryPtr()->declareSignalOut("filesAndDirsRequest");
    p_engineClient->getSignalFactoryPtr()->declareSignalIn("filesAndDirsReply");

    p_engineClient->connect("filesAndDirsReply", this, EXECUTOR(updateModel));

    SignalOut signal = p_engineClient->signalOut("filesAndDirsRequest");
    signal.addParameter("path", v_path);
    p_engineClient->emitSignal(signal);
}


FileBrowserWindow::~FileBrowserWindow(){
    delete p_engineClient;

}


void FileBrowserWindow::updateModel(const Parameters& params){
    QStringList dirsList = params.get("dirs").toString().split("\n");
    QStringList filesList = params.get("files").toString().split("\n");

    QStringList::const_iterator it;
    for(it = dirsList.constBegin(); it != dirsList.constEnd(); it++){
        p_fileTreeListWidget->addItem(*it + "/");
    }
    for(it = filesList.constBegin(); it != filesList.constEnd(); it++){
        p_fileTreeListWidget->addItem(*it);
    }

    p_pathLineEdit->setText(v_path);
}


void FileBrowserWindow::explore(QModelIndex index){
    QString newDir = index.data().toString();
    if(newDir.endsWith("/")){
        p_fileTreeListWidget->clear();
        SignalOut signal = p_engineClient->signalOut("filesAndDirsRequest");
        if(newDir == "../")
            v_path = v_path.section("/", 0, -3) + "/";
        else
            v_path = v_path + newDir;

        signal.addParameter("path", v_path);
        p_engineClient->emitSignal(signal);
    }
}
